package cn.hom1.controller;

import cn.hom1.exception.MyException;
import cn.hom1.model.entity.User;
import cn.hom1.model.enums.ResponseCode;
import cn.hom1.model.vo.ResponseVo;
import cn.hom1.service.UserService;
import com.google.code.kaptcha.Constants;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 后台页面控制器
 *
 * @author iksen
 * @date 2019-01-15 15:07
 */
@Controller
public class SystemController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private UserService userService;

    @RequestMapping({"","/index"})
    public String index(){
      return "system/index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(){
      return "system/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseVo login(String username, String password, String verification){
      if (StringUtils.isEmpty(username) || StringUtils.isEmpty(username) || StringUtils.isEmpty(verification)){
        return new ResponseVo(ResponseCode.FAILURE.getCode(),"非法参数！");
      }
      if (!verification.equals(request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY))){
        return new ResponseVo(ResponseCode.FAILURE.getCode(),"登陆失败！验证码输入错误。");
      }
      User user = userService.selectByUsername(username);
      if (null == user){
        user = userService.selectByEmail(username);
      }
      if (null != user){
        if (password.equals(user.getPassword())) {
          request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,null);
          return new ResponseVo(ResponseCode.SUCCESS.getCode(),"登陆成功！");
        }
      }
      return new ResponseVo(ResponseCode.FAILURE.getCode(),"登陆失败！账号或密码错误。");
    }

    @RequestMapping(value = "/test")
    public String exception(){
        Integer.parseInt("error");
      return "system/login";
    }
    @RequestMapping(value = "/test2")
    public String exception2(){
      throw new MyException("自定义异常", new Exception());
    }
}
